<?php
class memberModel extends Model{
	public $primaryKey='userid';
	public $table='member';
		
	
	public function __construct(){
		parent::__construct();
		
		
    /*
        格式 $this->_valid = array(
                    array('验证的字段名',0/1/2(验证场景),'报错提示','require/in(某几种情况)/between(范围)/length(某个范围)','参数')
        );

        array('goods_name',1,'必须有商品名','requird'),
        array('cat_id',1,'栏目id必须是整型值','number'),
        array('is_new',0,'in_new只能是0或1','in','0,1')
        array('goods_breif',2,'商品简介就在10到100字符','length','10,100')

    */
		
		$this->_auto = array(
			array('password','method','encode_password','force'),
			
			array('password','method','encode_password','notnull'),
		);
		$this->_valid = array(
			array('username',1,'用户名称不能为空！','require'),
			array('password',1,'密码不能为空！','require'),
			array('groupid',1,'所属组不能为空！','number'),
			
			array('username',1,'用户名称已存在！','callback','user_is_exists'),
		);
		$this->_auto_for_add = array(0);
		$this->_auto_for_mod = array(1);
		$this->_auto_for_select = array();
		
		$this->_valid_for_add = array(0,1,2,3);
		$this->_valid_for_mod = array(0,2,3);
		$this->_valid_for_select = array();
		
	}
	public function user_is_exists($username){
		if($this->action=='add'){
			$query="select `userid` from `{$this->full_table}` where `username`=:username";
			$r=$this->db->get_field($query,array('username'=>$username));
			if($r>0){
				return false;
			}
			return true;
		}
		if($this->action=='mod'){
			$userid=$this->userid;
			$query="select `userid` from `{$this->full_table}` where `username`=:username and `userid`!=:userid ";
			$r=$this->db->get_field($query,array('username'=>$username,'userid'=>$userid));
			if($r>0){
				return false;
			}
			return true;
		}
		return false;
	}
	public function encode_password($password){
		return md5($password);
	}
	//检测是否是创始人
	public function is_founder($user_id){
		return 1==$user_id;
	}
    //检测表单项不为空
    public function check_blank2($data){
        if(trim($data['old_password'])=='' or trim($data['password'])==''){
            return false;
        }
        $this->d=$data;
        return true;
    }
    //返回用户id
    private function get_id(){
        return $_SESSION['MY']['ID'];
    }
    //确认旧密码
    public function is_correct($f){
        $id=$this->get_id();
        $query="select `password` from `{$this->full_table}` where `userid`=:userid";
        $r=$this->db->get_field($query,array('userid'=>$id));
        return $this->encode_password($this->d[$f])==$r;
    }
    //更新密码
    public function update_pwd(){
        $id=$this->get_id();
        $pwd=$this->encode_password($this->d['password']);
        $query="update `{$this->full_table}` set `password`=:pwd where `userid`=:id";
        return $this->db->query($query,array('pwd'=>$pwd,'id'=>$id));
    }
}